<?php
/**
 * 日志操作统一入口
 * @文件名称: DmpLog.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\components;
use Yii;
class DmpLog
{
    /**
     * 常用日志调用统一入口
     *
     * @param $info
     * @param boolean $isError
     */
    public static function log($fiex, $isError = true, $info=[])
    {
        static::defineLogID();
        $time = DmpUtil::getDateBy(time());
        $logId = YII_LOG_ID;
        $server = DmpUtil::getHostName();
        if(is_array($fiex)){
            $fiex = serialize($fiex);
        }
        if(is_array($info)){
            $info = serialize($info);
        }

        $info = "[time: {$time}, fiex: {$fiex}, info: {$info}, logID: {$logId}, server: {$server}]";

        if($isError){
            self::error($info);
        }else{
            Yii::info($info);
        }
    }

    /**
     * @param $e \Exception |
     */
    public static function exception($e)
    {
        static::defineLogID();
        $time = DmpUtil::getDateBy(time());
        $code = $e->getCode();
        $file = $e->getFile();
        $line = $e->getLine();
        $message = $e->getMessage();
        $trace = $e->getTraceAsString();
        $logId = YII_LOG_ID;
        $server = DmpUtil::getHostName();

        $info = "[time: $time, e: [code: $code, file: $file, line: $line, message: $message, trace: $trace], logId: $logId, server: $server]";

        self::error($info);
    }

    /**
     * Log and send email
     *
     * @param $info
     */
    private static function error($info)
    {
        if(!is_string($info)){
            $info = json_encode($info);
        }

        static::defineLogID();
        Yii::error($info, Yii::$app->params['traceLevel']['error']);

        EmailUtil::sendBySwift(\Yii::$app->params['errorEmailList'], '['.YII_ENV.'-报警]', $info);
    }
    /**
     * 写入数据库的用户操作log
     *
     * @params bool $isUser true: 记录登陆用户的log, false: 记录不具有登录态的log
     */
    private static function opLog($route, $request, $isUser, $userId = '', $userName = '')
    {
    }

    /**
     * 记录日志到ELK
     *
     * ---------  Deprecate  ---------
     *
     * @param array $message 需要记录的日志
     * @param $level
     * @param string $category
     */
    public static function elkLog($message, $level, $category='default')
    {
        if ($category == 'default') {
            $category = Yii::$app->controller->id . '-' . Yii::$app->controller->action->id;
        }

        static::defineLogID();

        $data = [
            'LogID' => YII_LOG_ID,
            'server' => gethostname(),
            'message' => $message,
        ];
        if ($level == 'info') {
            Yii::info(json_encode($data, JSON_UNESCAPED_SLASHES), $category);
        } elseif ($level == 'error') {
            Yii::error(json_encode($data, JSON_UNESCAPED_SLASHES), $category);
        } elseif ($level == 'warning') {
            Yii::warning(json_encode($data, JSON_UNESCAPED_SLASHES), $category);
        } else {
            Yii::trace(json_encode($data, JSON_UNESCAPED_SLASHES), $category);
        }
    }

    public static function debug($data)
    {
        static::defineLogID();

        if (is_array($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL;
        } else {
            $data .= PHP_EOL;
        }

        $filePath = '/data/logs/group/debug.log';

        $ts = '[ ' . DmpUtil::getDateBy(time()) . ' ] [debug] ';

        file_put_contents($filePath, $ts, FILE_APPEND);
        file_put_contents($filePath, $data, FILE_APPEND);
    }

    public static function defineLogID()
    {
        defined('YII_LOG_ID') or define('YII_LOG_ID', md5(microtime().rand(0,100)));
    }
}

